//
//  ios_Director.mm
//  Prism
//
//  Created by Bas du Pre on 21-05-11.
//  Copyright 2011 UU. All rights reserved.
//

#include "global.h"
#if PRISM_TARGET_SDL
#include "sdl/sdl_global.h"

#include "graphics/Director.h"

using namespace Prism;
using namespace Prism::Graphics;

void Director::native_init() {
    sdlScreen = NULL;
    
    //Start SDL
    //SDL_Init( SDL_INIT_EVERYTHING );
    if(SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        PRISM_ERROR("Unable to init SDL: %s\n", SDL_GetError());
    }
    
    sdlScreen = SDL_SetVideoMode(800, 600, 32, SDL_OPENGL);
    if (sdlScreen == NULL)
    {
        PRISM_ERROR("Unable to set %dx%d OpenGL video: %s\n", _winSize.width, _winSize.height, SDL_GetError());
    }
    
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    
    // Set the OpenGL state after creating the context with SDL_SetVideoMode
	glViewport(0, 0, 800, 600);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, 800, 600, 0, -1, 1);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
    SDL_GL_SetSwapInterval(1);

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    
    onWinSizeChanged += delegate(this, &Director::native_onWinSizeChangedResizeOpenGL);
    setWinSize(Prism::Size(800, 600));
    
    glClearColor(0, 0, 0, 0);
	glEnable(GL_TEXTURE_2D); // Need this to display a texture
    
    SDL_startTime = SDL_GetTicks();
}

void Director::native_deInit() {
    SDL_FreeSurface(sdlScreen);
    SDL_Quit();
}

void Director::native_updateAllNodesUnder(Node* node, PFloat dt) {
    UpdateEventArgs e(dt);
    node->onUpdate(node, &e);
    for (unsigned int i = 0; i < node->_childs.length(); i++) {
        native_updateAllNodesUnder(node->_childs[i], dt);
    }
}

void Director::native_beforeDrawScene() {
    static long lastTicks = SDL_startTime;
    long ticks = SDL_GetTicks();
    native_updateAllNodesUnder(_scene, (ticks - lastTicks) / (PFloat)1000.0);
    
    lastTicks = ticks;
    
    // Clear the screen before drawing
    glClear(GL_COLOR_BUFFER_BIT);    
}

void Director::native_afterDrawScene() {
    SDL_GL_SwapBuffers();
}

PFloat Director::native_fps() {
    if (SDL_frames == 0)
        return 0;
    
    PFloat fps = (SDL_frames/(float)(SDL_GetTicks() - SDL_startTime)) * 1000;
        
    return fps;
}

void Director::native_sceneUpdate() {
    
}

void Director::native_onWinSizeChangedResizeOpenGL(void* sender, EventArgs *e) {
    
}

#endif
